import React from 'react';
import * as mobx from 'mobx';
import {inject,observer} from 'mobx-react';
import {routerShape} from 'react-router';
import {Link} from 'react-router';
import {WeaReportGroup,WeaTop,WeaTab,WeaRightMenu,WeaSearchGroup,WeaFormItem,WeaSelect,WeaLocaleProvider} from 'ecCom';
import {Button,Modal,message} from 'antd';
import isEmpty from 'lodash/isEmpty';
import SaveAsModal from '../../public/wf-save-as-template';
import * as WORKFLOW_CUSTOMFORM from '../../apis/customReportForm';
import cloneDeep from 'lodash/cloneDeep';
import Style from '../../style/customReportForm.less';
const getLabel = WeaLocaleProvider.getLabel;

@inject('wfViewReportStore')

@observer

export default class Main extends React.Component {

    static contextTypes = {
        router: routerShape
    }

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        const {wfViewReportStore} = this.props;
        const reportid = this.props.location.query.reportid || '';
        const templateid = this.props.location.query.tabKey || 0;
        wfViewReportStore.initDatas({reportid,templateid});
    }

    componentWillUnmount () {
        const {wfViewReportStore} = this.props;
        wfViewReportStore.clearState();
    }

    dealValues () {

        const value = this.report.get();

        let checkArr = Object.keys(value).filter((item,index)=>{
            if(value[item].checked){
                return true;
            }else{
                return false;
            }
        });

        let selectfieldids = checkArr.join(',');

        if(!selectfieldids){
            return '';
        }

        let params = {};

        checkArr.forEach((item,index)=>{
            params = {...params,...value[item].value}
        })

        params.selectfieldids = selectfieldids;

        return params;

    }

    doSearch() {

        const {wfViewReportStore} = this.props;
        const {reportid,title,key,hasFormRight,dataRanage,rightKey} = wfViewReportStore;

        let params = this.dealValues();
        let tabKey = key;
        let query = {
            reportid,
            title,
            tabKey,
            ...params,
        };
        if (hasFormRight) {
            query = {...query,dataRanage,rightKey};
        }
        this.context.router.push({
            pathname : "/main/workflow/viewCustomResult",
            query : {
                ...query
            }
        });

    }

    reset() {
        const {wfViewReportStore} = this.props;
        let {tabs,key,hasFormRight} = wfViewReportStore;
        let config = [];

        let newTabs = cloneDeep(mobx.toJS(tabs)), newTabsNext = [];

        newTabs = newTabs.map((item,index)=>{
            const curItem = cloneDeep(mobx.toJS(item))
            newTabsNext.push(curItem);
            if(Number(key) === Number(item.key)) {
                config = item.config;
                item.config = [];
                if(hasFormRight){
                    wfViewReportStore.setState({dataRanage:item.dataRanage});
                }
                // let timer = setTimeout(()=>{
                //     item.config = config;
                // },0);
            }
            return item;
        })

        wfViewReportStore.resetTabs(newTabs,newTabsNext)

    }

    deleteTemplate () {
        const {wfViewReportStore} = this.props;
        const {key} = wfViewReportStore;
        let params = {templateid:key};
        message.loading(getLabel(84024,'正在删除，请稍后...',0));
        WORKFLOW_CUSTOMFORM.getCRDeleteTemplate(params).then((datas)=>{
            if(datas.success){
                message.destroy();
                message.success(getLabel(20461,'删除成功'));
                wfViewReportStore.loadDatas('delete');
                this.report.reset();
            }else {
                message.destroy();
                message.error(getLabel(20462,'删除失败'));
            }
        })
    }

    deleteCondition(_this) {
        Modal.confirm({
            title: getLabel(131329,'信息确认'),
            content: getLabel(129890,'确定要删除吗？'),
            okText:  getLabel(83446,'确定'),
            cancelText: getLabel(31129,'取消'),
            onOk() {
                _this.deleteTemplate();
            },
        })
    }

    saveAsTemplate () {
        let params = this.dealValues();
        if (!params) {
            message.warning(getLabel(383625,'请选择报表条件'));
            return ;
        }
        this.saveAsModal.click(true);
    }

    saveAsOk (v) {
        let templatename = v;
        let params = this.dealValues();
        if (!params) {
            message.warning(getLabel(383625,'请选择报表条件'));
            return ;
        }
        params = {...params,templatename};
        this.addTemplate(params);
    }

    addTemplate (params = {}) {
        const {wfViewReportStore} = this.props;
        const {reportid,hasFormRight,rightKey,dataRanage} = wfViewReportStore;

        let newParams = {...params,reportid};
        if(hasFormRight){
            newParams = {...newParams,rightKey,dataRanage};
        }

        message.loading(getLabel(23278,'正在保存，请稍后...',0));
        WORKFLOW_CUSTOMFORM.getCRAddTemplate(newParams).then((datas)=>{
            if(datas.success){
                message.destroy();
                message.success(getLabel(83551,'保存成功'));
                // this.report.reset();
                wfViewReportStore.loadDatas('add',datas.templateid);
            }else {
                message.destroy();
                message.error(getLabel(84544,'保存失败'));
            }
        });
    }

    save () {
        const {wfViewReportStore} = this.props;
        const {key} = wfViewReportStore;
        let templateid = key;
        let params = this.dealValues();
        if (!params) {
            message.warning(getLabel(383625,'请选择报表条件'));
            return ;
        }
        params = {...params,templateid};
        this.editTemplate(params);
    }

    editTemplate (params = {}) {
        const {wfViewReportStore} = this.props;
        const {reportid,hasFormRight,rightKey,dataRanage} = wfViewReportStore;
        let newParams = {...params,reportid};
        if(hasFormRight){
            newParams = {...newParams,rightKey,dataRanage};
        }
        message.loading(getLabel(383500,'正在修改，请稍候...',0));
        WORKFLOW_CUSTOMFORM.getCRAddTemplate(newParams).then((datas)=>{
            if(datas.success){
                message.destroy();
                wfViewReportStore.loadDatas('edit');
                message.success(getLabel(383312 ,'修改成功'));
            }else {
                message.destroy();
                message.error(getLabel(31436,'修改失败'));
            }
        });
    }

    goBack () {
        this.context.router.push({
            pathname : "/main/workflow/customReportForm",
        });
    }

    getButtons() {
        const {wfViewReportStore} = this.props;
        const {key} = wfViewReportStore;
        let btns = [];

        // btns.push(
        //     (<Button type="primary"><Link to="/main/workflow/customReportForm">返回</Link></Button>)
        // )

        if (Number(key) === 0) {
            btns.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qxs7km@search`} type="primary" onClick={() => this.doSearch()}>{getLabel(197,'搜索')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@i6f8uw@reset`} type="primary" onClick={() => this.reset()}>{getLabel(2022,'重置')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x7eb43@saveAsTemplate`} type="primary" onClick={() => this.saveAsTemplate()}>{getLabel(18418,'存为模板')}</Button>),
            )
        } else {
            btns.push(
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t2d0mf@search`} type="primary" onClick={() => this.doSearch()}>{getLabel(197,'搜索')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@p3rtfi@reset`} type="primary" onClick={() => this.reset()}>{getLabel(2022,'重置')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@r119tx@save`} type="primary" onClick={() => this.save()}>{getLabel(86,'保存')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@w3fv2j@saveAsTemplate`} type="primary" onClick={() => this.saveAsTemplate()}>{getLabel(131623,'另存为')}</Button>),
                (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@32cd3m@deleteCondition`} type="primary" onClick={() => this.deleteCondition(this)}>{getLabel(91,'删除')}</Button>),
            );
        }

        return btns;
    }

    switchTab(key) {
        const {wfViewReportStore} = this.props;
        this.report && this.report.reset();
        wfViewReportStore.switchTabs(Number(key));
    }

    dropMenuDatas() {
        const {wfViewReportStore} = this.props;
        const {key} = wfViewReportStore;
        let btns = [];

        if (Number(key) === 0) {
            btns.push(
                {
                    key: "1",
                    icon: <i className="icon-coms-search"/>,
                    content: getLabel(197,'搜索'),
                    onClick: key => {
                        this.doSearch()
                    }
                },{
                    key: "2",
                    icon: <i className="icon-coms-Reset"/>,
                    content: getLabel(2022,'重置'),
                    onClick: key => {
                        this.reset()
                    }
                },{
                    key: "4",
                    icon: <i className="icon-coms-go-back"/>,
                    content: getLabel(383624,'返回'),
                    onClick: key => {
                        this.goBack();
                    }
                },{
                    key: "3",
                    icon: <i className="icon-coms-Journal-o"/>,
                    content: getLabel(18418,'存为模板'),
                    onClick: key => {
                        this.saveAsTemplate();
                    }
                }
            )
        } else {
            btns.push(
                {
                    key: "1",
                    icon: <i className="icon-coms-search"/>,
                    content: getLabel(197,'搜索'),
                    onClick: key => {
                        this.doSearch()
                    }
                },{
                    key: "2",
                    icon: <i className="icon-coms-Reset"/>,
                    content: getLabel(2022,'重置'),
                    onClick: key => {
                        this.reset();
                    }
                },{
                    key: "6",
                    icon: <i className="icon-coms-go-back"/>,
                    content: getLabel(383624,'返回'),
                    onClick: key => {
                        this.goBack();
                    }
                },{
                    key: "3",
                    icon: <i className="icon-coms-Preservation"/>,
                    content: getLabel(86,'保存'),
                    onClick: key => {
                        this.save();
                    }
                },{
                    key: "4",
                    icon: <i className="icon-coms-Preservation"/>,
                    content: getLabel(131623,'另存为'),
                    onClick: key => {
                        this.saveAsTemplate();
                    }
                },{
                    key: "5",
                    icon: <i className="icon-coms-form-delete"/>,
                    content: getLabel(91,'删除'),
                    onClick: key => {
                        this.deleteCondition(this);
                    }
                }
            )
        }

        return btns;
    }

    // lengthWarning(length) {
    //     message.warning(`模板名称长度不能超过${length}个字符！`);
    // }

    getDatasJurisdiction () {
        const {wfViewReportStore} = this.props;
        const {selectOption,dataRanage,selectLabel,dataRanageLabel,dataRanageInfo1,dataRanageInfo2} = wfViewReportStore;

        let rangeValue = Number(dataRanage) === 1 ? dataRanageInfo1 : dataRanageInfo2;
        return (
            <div>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@7yom94`}
                    label={selectLabel}
                    labelCol={{span: 5,offset: 7}}
                    wrapperCol={{span: 5}}
                >
                    <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@pgaf6y`}
                        options={selectOption.slice()}
                        value={dataRanage}
                        detailtype={3}
                        onChange={v => {
                            wfViewReportStore.setState({dataRanage:v})
                        }}
                    />
                </WeaFormItem>
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@wk0p8h`}
                    label={dataRanageLabel}
                    labelCol={{span: 5,offset: 7}}
                    wrapperCol={{span: 5}}
                >
                    <p style={{lineHeight:'30px'}}>{rangeValue}</p>
                </WeaFormItem>
            </div>
        )
    }

    getReportGroup () {

        const {wfViewReportStore} = this.props;
        let {tabs:oriTabs,key,renderComponent = ''} = wfViewReportStore;
        let config = [];
        let tabs = cloneDeep(mobx.toJS(oriTabs));

        tabs && tabs.forEach((item, index) => {
            // tabs[index].title = item.tabname;
            if(Number(key) === Number(item.key)){
                config = item.config.length === 0 ? [] : [...item.config];
            }
        })

        config = mobx.toJS(config);

        let showAll = Number(key) !== 0 ; //全部条件都展开，其它只展开选择的;

        let out = !isEmpty(config) ?
            <WeaReportGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaReportGroup@42bqo6`}
                ref={report => this.report = report}
                // needChangeCheck={true}
                config={config}
                hasShowAll={showAll}
                onChange={this.doReportGroupChange.bind(this)}
            /> : <div></div>;

        return (
            out
        )
    }
    handleOk = (v) => this.saveAsOk(v);

    render() {
        const {wfViewReportStore} = this.props;
        let {tabs:oriTabs,loading,title,key,hasFormRight,titleLabel,conditionLabel,renderComponent = ''} = wfViewReportStore;
        let tabs = cloneDeep(mobx.toJS(oriTabs));

        tabs && tabs.forEach((item, index) => {
            tabs[index].title = item.tabname;
        })

        return (
            <div className="wf-viewReport">
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@c5axg6`} datas={this.dropMenuDatas()}>
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@065fcl`}
                        title={title}
                        loading={loading}
                        icon={<i className="icon-coms-workflow"/>}
                        iconBgcolor='#0079DE'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.dropMenuDatas()}
                    >
                        <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@j0qs5l`}
                            datas={tabs}
                            keyParam="key"  //主键
                            onChange={(key) => this.switchTab(key)}
                            selectedKey={key}
                        />
                        {
                            hasFormRight ?
                                <div>
                                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@gfmzfc`}
                                        title={titleLabel}
                                        showGroup={true}
                                        items={[
                                            {
                                                com : this.getDatasJurisdiction()
                                            }
                                        ]}
                                        col={1}
                                    />
                                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@5byp6j`}
                                        title={conditionLabel}
                                        showGroup={true}
                                        items={[
                                            {
                                                com : this.getReportGroup()
                                            }
                                        ]}
                                        col={1}
                                    />
                                </div>
                                : this.getReportGroup()
                        }
                    </WeaTop>
                </WeaRightMenu>
                <SaveAsModal ecId={`${this && this.props && this.props.ecId || ''}_SaveAsModal@g2j9m0`}
                    ref={(saveAsModal)=>this.saveAsModal = saveAsModal}
                    type="modal"
                    length={100}
                    handleOk={this.handleOk}
                    // lengthWarning={length => this.lengthWarning(length)}
                />
            </div>
        )
    }

    doReportGroupChange(v,ids,isFirst){
        this.doWorkflowConditionChange(v,ids,isFirst);
    }

    //流程浏览框联动节点浏览框
    doWorkflowConditionChange(v,ids,isFirst) {
        const {wfViewReportStore} = this.props;
        const {tabs,key,updateConfigItem} = wfViewReportStore;
        let _tabs  =  mobx.toJS(tabs);
        _tabs && _tabs.forEach((item,index)=>{
            if(Number(key) === Number(item.key)){
                const {config} = item;
                const configitem = config[ids];
                if(configitem && configitem.key  === '-12') { //工作流程
                    const targetfieldid  = '-13';               //节点
                    for(let i = 0 ;i < config.length ;i++) {
                        if(config[i].key  === targetfieldid) {
                            let targetConfigItemconfig  = config[i].config[0];
                            if(targetConfigItemconfig) {
                                let dataParams  = targetConfigItemconfig.browserConditionParam.dataParams;
                                let completeParams = targetConfigItemconfig.browserConditionParam.completeParams;
                                targetConfigItemconfig.browserConditionParam.dataParams = {...dataParams,'workflowid':v['field-12_value1']};
                                targetConfigItemconfig.browserConditionParam.completeParams = {...completeParams,'workflowid':v['field-12_value1']};
                                updateConfigItem(i,0,targetConfigItemconfig);
                                return;
                            }
                        }
                    }
                }
            }
        });
    }
}
